Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

222
Visualizações
Graph | DFS | Matrix | Find rectangle coordinates

Given a matrix of 1s with one or several rectangles inside represented by 0, return the upper left corner and lower right corner coordinates.

I've added my code below which follows a basic grid graph DFS pattern but I can't quite figure out how to return the coordinates without increasing the overall runtime. Would love some help if someone could bring me across the finish line.

const findCoordinates = (grid) => {
  const coordinates = [];
  // const visited = new Set();
  for (let r = 0; r < grid.length; r++) {
    for (let c = 0; c < grid[0].length; c++) {
      const rectangle = dfs(grid, r, c, new Set());
      if (rectangle) coordinates.push(rectangle);
    }
  }
  return coordinates;
}

const dfs = (grid, r, c, visited) => {
  if (invalidPos(grid, r, c)) return null;
  const pos = r + ',' + c;
  if (visited.has(pos)) return null;
  visited.add(pos);
  dfs(grid, r, c, visited);
  dfs(grid, r, c, visited);
  dfs(grid, r, c, visited);
  dfs(grid, r, c, visited);
  const rectangle = visited.entries();
  // return [[rectangle[0].split(''), rectangle[2].split('')], [rectangle[rectangle.length - 2].split(''), rectangle[rectangle.length - 1].split('')]];
}

const invalidPos = (grid, r, c) => {
  const invalidRow = r < 0 || r >= grid.length;
  const invalidCol = c < 0 || c >= grid[0].length;
  return invalidRow || invalidCol || grid[r][c] === 1;
}

const grid1 =
[
  [1,1,1,1,1],
  [1,0,0,1,1],
  [1,0,0,1,1],
  [1,1,1,1,1]
];
console.log(findCoordinates(grid1));
// should return [[[1,1],[2,2]]]

const grid2 =
[
  [1,1,1,1,1],
  [1,0,0,1,1],
  [1,0,0,1,1],
  [1,1,1,1,0]
];
console.log(findCoordinates(grid2));
// should return [[[1,1],[2,2]],[[3,4],[3,4]]]

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda